<template>
  <div class="answer-page">
    <div class="editor-container">
      <md-editor
        v-model="markdownContent"
        class="markdown-editor"
        placeholder="用Markdown格式编辑你的题解..."
      />
    </div>
    <div class="actions">
      <button @click="submit">发布题解</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { useRoute, useRouter } from "vue-router";
import { QuestionControllerService, QuestionVO } from "../../../generated";
import message from "@arco-design/web-vue/es/message";

const route = useRoute();
const markdownContent = ref("");
const questionId = route.params.id;
const question = ref<QuestionVO>();

// 页面加载时，请求数据
onMounted(() => {
  console.log("请求的题目id" + questionId);
  loadQuestionVO();
});

const loadQuestionVO = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    questionId as any
  );
  if (res.code === 0) {
    question.value = res.data;
    console.log(question.value?.title);
  } else {
    console.log("请求出错");
    message.error("加载失败，" + res.message);
  }
};

// 监听 question 的变化，并在变化时更新 markdownContent
watch(
  question,
  (newQuestion) => {
    const questionTitle = newQuestion?.title || "";
    const submitLanguage = "java";
    markdownContent.value = `
# 题目标题: ${questionTitle} 

## 思路
（在这里编写你的思路）

## 解题过程
（在这里编写解题过程）

## 复杂度
- 时间复杂度: （在这里填写时间复杂度）
- 空间复杂度: （在这里填写空间复杂度）

## 代码
\`\`\` ${submitLanguage}
\`\`\`
  `;
  },
  { immediate: true }
);

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (questionId: string) => {
  router.push({
    path: `/view/question/${questionId}`,
  });
};

const submit = async () => {
  const solutionData = {
    questionId: questionId,
    content: markdownContent.value,
  };

  const res = await QuestionControllerService.addQuestionSolutionUsingPost(
    solutionData
  );
  if (res.code === 0) {
    message.success("发布题解成功！");
    toQuestionPage(questionId as string);
  } else {
    message.error("发布题解失败，" + res.message);
  }
};
</script>

<style>
.answer-page {
  max-width: 1200px;
  margin: 0 auto;
}

.editor-container {
  display: flex;
  justify-content: space-between;
}

.markdown-editor {
  width: 100%;
  height: 600px;
  margin-bottom: 20px;
}

.markdown-preview {
  width: 48%;
  height: 600px;
  overflow-y: auto;
}

.actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}
</style>
